package handler

import (
	"gift/api/request"
	"gift/internal/dao"
	"gift/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddLive(c *gin.Context) {
	var req request.AddLive
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	live := model.Live{
		Name:  req.Name,
		Text:  req.Text,
		Title: req.Title,
	}
	if !dao.Create(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live,
	})
	return
}

func FindLive(c *gin.Context) {
	var req request.FindLive
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	live := model.Live{
		Id: req.Id,
	}
	if !dao.FindAll(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live,
	})
	return
}

func UpdateLive(c *gin.Context) {
	var req request.UpdateLive
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	if !dao.GetOneById(req.Id, &live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	live = model.Live{
		Id:    req.Id,
		Name:  req.Name,
		Text:  req.Text,
		Title: req.Title,
	}
	if !dao.Update(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "更新失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live,
	})
	return
}

func DeleteLive(c *gin.Context) {
	var req request.DeleteLive
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	if !dao.GetOneById(req.Id, &live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	if !dao.Delete(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": live,
	})
	return
}
